import json
import xlsxwriter
from io import BytesIO
from apis import api_routes
from flask import g, request, jsonify, Response

from models.facility.facility import Facility
from security.decoration import certification
from models.logs.logs import Logs
from public.local import date_type
from datetime import datetime, timedelta
from sqlalchemy import and_
from typing import List
from models.logs.stationlog import StationLog
from urllib.parse import unquote, quote
from public.local import local_time


@api_routes.route("/stationlog", methods=["GET"])
def func_stationlog_get_api():
    """
    查询PLC-MES交互日志
    http://127.0.0.1:8080/api/stationlog
    Content-Type=application/x-www-form-urlencoded
    methods=["GET"]
    {
    "index"         int      ****  第几页，默认为1
    "size"          int      ****  每页数据多少, 默认每页10条数据
    "start"        string          开始时间, 默认今天时间  格式 %Y-%m-%d
    "finish"       string          结束时间，默认今天时间  格式 %Y-%m-%d
    "facility_id"  int             数据库设备ID
    }
    :return:
        {'status': 200, 'data': resp, "index": index, "size": size, "total": count, "pages": page}
    ---
    tags:
      - MES与PLC交互日志
    """
    size = request.args.get("size", default=10, type=int)
    index = request.args.get("index", default=1, type=int)
    start = request.args.get("start", default=None, type=str)
    finish = request.args.get("finish", default=None, type=str)
    ft_id = request.args.get("facility_id", default=None, type=int)

    arg0, arg1 = start, finish
    if start is None:
        arg0 = date_type()
    else:
        arg0 = datetime.strptime(start, "%Y-%m-%d")

    if finish is None:
        arg1 = date_type() + timedelta(days=1) - timedelta(seconds=1)
    else:
        arg1 = datetime.strptime(finish, "%Y-%m-%d") + timedelta(days=1) - timedelta(seconds=1)

    parameter: list = [StationLog.time >= arg0, StationLog.time < arg1]
    if ft_id is not None:
        parameter.append(StationLog.ft_id == ft_id)

    count = g.session.query(StationLog.id).filter(and_(* parameter)).count()
    page: int = int((count / size) + 1) if (count / size) > int(count / size) else int(count / size)
    db_data: List[StationLog] = g.session.query(StationLog).filter(and_(* parameter)).order_by(StationLog.id).offset((index - 1) * size).limit(size).all()
    resp: list = []
    for f_itr in db_data:
        facility: Facility = g.session.query(Facility).filter(Facility.id == f_itr.ft_id).first()
        resp.append({
            "time": f_itr.time.strftime("%Y-%m-%d %H:%M:%S"),
            "sequence": f_itr.sequence,
            "ft_serials": facility.serials,
            "ft_name": facility.name,
            "title": f_itr.title,
            "address": f_itr.address,
            "value": f_itr.value,
            "feedback": f_itr.feedback,
            "message": f_itr.message,
            "datainfo": f_itr.datainfo,
            "dataios": f_itr.dataios
        })

    doc: dict = {
        "time": "记录创建时间 4",
        "sequence": "产品序列SN 3",
        "ft_serials": "设备你编号 1",
        "ft_name": "设备名称 2",
        "title": "PLC信号触发触发类型 5",
        "address": "PLC触发地址 6",
        "value": "PLC触发值 7",
        "feedback": "MES处理结果 8",
        "message": "备注 9",
        "datainfo": "总体信息 10",
        "dataios": "采集PLC信息汇总 11",
    }
    return jsonify({'status': 200, 'data': resp, "index": index, "size": size, "total": count, "pages": page, "doc": doc})

